package com.jiankangjin.transsystem.services.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.jiankangjin.common.json.jackson.JSONUtil;
import com.jiankangjin.common.uuid.IdGenerator;
import com.jiankangjin.encryptKit.EncryptUtil;
import com.jiankangjin.trading.dao.IChannelDao;
import com.jiankangjin.trading.dao.IDiagDataDao;
import com.jiankangjin.trading.dao.IMerInfoDao;
import com.jiankangjin.trading.dao.IOrderAffiliatedDao;
import com.jiankangjin.trading.dao.IOrderDataDao;
import com.jiankangjin.trading.dao.IOrderDetailDataDao;
import com.jiankangjin.trading.entity.ChannelEntity;
import com.jiankangjin.trading.entity.DiagDataEntity;
import com.jiankangjin.trading.entity.MerInfoEntity;
import com.jiankangjin.trading.entity.OrderAffiliatedEntity;
import com.jiankangjin.trading.entity.OrderDataEntity;
import com.jiankangjin.trading.entity.OrderDetailDataEntity;
import com.jiankangjin.transsystem.common.Constant;
import com.jiankangjin.transsystem.services.CreateOrderServices;
import com.jiankangjin.transsystem.services.PayOrderServices;
import com.jiankangjin.transsystem.util.StringUtil;
import com.jiankangjin.transsystem.util.TimeUtil;
import com.jiankangjin.transsystem.vo.CreateVo;
import com.jiankangjin.transsystem.vo.DiagDataVo;
import com.jiankangjin.transsystem.vo.OrderDetailDataVo;
import com.jiankangjin.transsystem.vo.PayOrderVo;

/**
 * @author liuzy 
 * @date 2014年12月11日 下午4:36:41 
 */
@Service
public class CreateOrderServicesImpl implements CreateOrderServices{
	private static final Log log = LogFactory.getLog(CreateOrderServicesImpl.class);

	@Autowired
	private PayOrderServices payOrderServices;
	
	@Autowired
	private IMerInfoDao iMerInfoDao;
	
	@Autowired
	private IOrderDataDao iOrderDataDao;

	@Autowired
	private IOrderDetailDataDao iOrderDetailDataDao;

	@Autowired 
	private IDiagDataDao iDiagDataDao;

	@Autowired
	private  IOrderAffiliatedDao iOrderAffiliatedDao;

	@Autowired
	private IChannelDao iChannelDao;
	
	/**
	 * @return
	 */
	@Override
	public CreateVo createOrderV002(String module_id, String version,
			String sign, String merchant_order_id, String merchant_id,
			String store_name, Integer total_fee, String currency,
			String content, String goods_count, String goods_detail,
			String diag_detail, Boolean is_tip, String buyer_name,
			String buyer_cellphone, String page_callback,
			String order_callback, String comment,String busi_type, String token,
			String operator_id, String operator_name, String order_total_fee,
			String discount_fee, String discount_comment, String detail,
			String ext1, String ext2) {
		CreateVo createVo = new CreateVo();
        MerInfoEntity merInfo = iMerInfoDao.selectByPrimaryKey(merchant_id);
        if (merInfo==null) {
			log.error("merchant_id"+merchant_id+"商户编号不存在");
			createVo.setResp_status("9999");
            return createVo;
        }
		//取出生成的订单号
		String ORDERID = IdGenerator.getId();
		//获取系统时间
        Calendar c = Calendar.getInstance();
        OrderDataEntity orderData = new OrderDataEntity();
        orderData.setId(ORDERID);
        orderData.setMerId(merchant_id);
        orderData.setOrdRegTime(TimeUtil.getTime(c.getTime()));
        c.add(Calendar.DAY_OF_MONTH, 1);//明天过期
        orderData.setOrdExprTime(TimeUtil.getTime(c.getTime()));//订单过期时间
        orderData.setPayStat("0000");
        orderData.setPayAmt("0");
        orderData.setOrdStat("0000");
        orderData.setRefundStat("0000");
        orderData.setRefundCnt("0");
        orderData.setRefundAmt("0");
        orderData.setFeeAmt("0");
        orderData.setChnlFeeAmt("0");
        orderData.setMerOrdId(merchant_order_id);
        orderData.setOrdAmt(total_fee.toString());
        orderData.setOrdCry(currency);
        orderData.setMerFrwdUrl(page_callback);
        orderData.setMerNotfUrl(order_callback);
        orderData.setOperatorId(operator_id);
        orderData.setOperatorName(operator_name);
        //订单表入库
        iOrderDataDao.insert(orderData);
        
        
        
//        //取出商户其他信息
//        Merchant merchant = merchantServices.byMerchant(pid);
//
//        //查询商户编号是否存在
//        if (merchant == null) {
//            restMap.put("errMsg", "商户编号不存在，不能支付");
//            return restMap;
//        }
//
//        String signKey = merchant.getMerchantSummaryKey();
//        String privateKey = merchant.getMerchantPrivateDecrypt();


        if (StringUtil.isNotEmpty(goods_detail)) {
            if (goods_detail.indexOf(":") == -1) {
                try {
                	byte[] dData = EncryptUtil.dByPrivateKey(goods_detail.getBytes("utf-8"), "");
                	if (dData == null) {
                		log.error("merchant_id:" + merchant_id + "，detail["+goods_detail+"]商户明细解密失败");
                		createVo.setResp_status("9999");
                		return createVo;
                	}
					detail = new String(dData, "utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
            }
            //解析订单详情
            List<OrderDetailDataVo> orderDetailDataVos = JSONUtil.fromJSON(goods_detail, new TypeReference<List<OrderDetailDataVo>>(){});
            OrderDetailDataEntity orderDetailData;
            //循环遍历，插入订单详情表
            for (OrderDetailDataVo orderDetailDataVo : orderDetailDataVos) {
            	orderDetailData = new OrderDetailDataEntity();
            	orderDetailData.setId(IdGenerator.getId());
            	orderDetailData.setOrdId(ORDERID);
            	orderDetailData.setMerId(merchant_id);
            	orderDetailData.setMerOrdId(merchant_order_id);
            	orderDetailData.setWaresId(orderDetailDataVo.getGoods_id());
            	orderDetailData.setWaresType(orderDetailDataVo.getGoods_type());
            	orderDetailData.setApCode(orderDetailDataVo.getAp_code());
            	orderDetailData.setBatNo(orderDetailDataVo.getBat_no());
            	orderDetailData.setLogCode(orderDetailDataVo.getLog_code());
            	orderDetailData.setNdCode(orderDetailDataVo.getNd_code());
            	orderDetailData.setMiCode(orderDetailDataVo.getMi_code());
            	orderDetailData.setMiType(orderDetailDataVo.getMi_type());
            	orderDetailData.setWaresName(orderDetailDataVo.getGoods_name());
            	orderDetailData.setCmName(orderDetailDataVo.getCm_name());
            	orderDetailData.setChName(orderDetailDataVo.getCh_name());
            	orderDetailData.setStd(orderDetailDataVo.getStd());
            	orderDetailData.setUnit(orderDetailDataVo.getUnit());
            	orderDetailData.setPrice(new Long(orderDetailDataVo.getGoods_price()));
            	orderDetailData.setCurrency("156");
            	orderDetailData.setQuantity(new Long(orderDetailDataVo.getGoods_quantity()));
            	orderDetailData.setAmount(new Long(orderDetailDataVo.getGoods_price() * orderDetailDataVo.getGoods_quantity()));
            	orderDetailData.setShowUrl(orderDetailDataVo.getGoods_url());
            	iOrderDetailDataDao.insert(orderDetailData);
            }

        }
        if (!StringUtils.isEmpty(diag_detail)) {
            //解析诊断信息详情
            List<DiagDataVo> diagDataVos = JSONUtil.fromJSON(diag_detail, new TypeReference<List<DiagDataVo>>() {
            });
            int diagVos = diagDataVos.size();
            if (diagVos > 0) {
                DiagDataEntity diagData;

                for (DiagDataVo diagDataVo : diagDataVos) {
                    if (StringUtil.isEmpty(diagDataVo.getDiag_code())) {
                        log.error("DiagCode:" + diagDataVo.getDiag_code() + "诊断代码  为必填项不能为空");
                        createVo.setResp_status("9999");
                        return createVo;
                    }
                    diagData = new DiagDataEntity();
                    diagData.setId(IdGenerator.getId());
                    diagData.setOrdId(ORDERID);
                    diagData.setMerId(merchant_id);
                    diagData.sethId(diagDataVo.getH_id());
                    diagData.sethName(diagDataVo.getH_name());
                    diagData.setDiagCode(diagDataVo.getDiag_code());
                    diagData.setDiagName(diagDataVo.getDiag_name());
                    diagData.setDiagComment(diagDataVo.getDiag_comment());
                    diagData.setCrdUser("张三");
                    diagData.setUpdUser("0001");
                    diagData.setState("1");
                    iDiagDataDao.insert(diagData);
                }
            }
        }
        //入库订单附属表
        OrderAffiliatedEntity orderAffiliated = new OrderAffiliatedEntity();
        if (is_tip == true) {
            orderAffiliated.setIsTip(1 + "");
        } else {
            orderAffiliated.setIsTip(0 + "");
        }
        orderAffiliated.setId(IdGenerator.getId());
        orderAffiliated.setOrderId(ORDERID);
        orderAffiliated.setModuleId(module_id);
        orderAffiliated.setOrderVersion(version);
        orderAffiliated.setStoreName(store_name);
        orderAffiliated.setOrderContent(content);
        orderAffiliated.setGoodsCount(goods_count);
        orderAffiliated.setGoodsDetail(goods_detail);
        orderAffiliated.setDiagDetail(diag_detail);
        orderAffiliated.setBuyerName(buyer_name);
        orderAffiliated.setBuyerCellphone(buyer_cellphone);
        orderAffiliated.setOrderComment(comment);
        orderAffiliated.setOrderTotalFee(order_total_fee);
        orderAffiliated.setDiscountFee(discount_fee);
        orderAffiliated.setDiscountComment(discount_comment);
        orderAffiliated.setBusiType(busi_type);
        iOrderAffiliatedDao.insert(orderAffiliated);
        //返回相应信息
        List<ChannelEntity> channels = iChannelDao.listAll();
        
        List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		Map<String, Object> map3 = null;
		for (ChannelEntity enty : channels) {
			map3 = new HashMap<String, Object>();
			map3.put("id", enty.getId());
			map3.put("channel_name", enty.getChannelName());
			map3.put("channel_type", enty.getChannelType());
			map3.put("channel_amt", "10000");
			map3.put("channel_comment", enty.getChannelFeeType());
			list2.add(map3);
		}
		createVo.setResp_status(Constant.RESP_STAT_CODE_0000);
        createVo.setOrder_id(ORDERID);
        createVo.setChannel(JSONUtil.toJSON(list2, List.class));
        createVo.setMsg(Constant.RESP_STAT_MSG_0000);
        createVo.setSign("translkdjgersign");
        log.info("订单创建完成");
		return createVo;
	}

	/**
	 * 版本=v0.3的方法
	 */
	@Override
	public CreateVo createOrderV030(String module_id, String version,
			String sign, String merchant_order_id, String merchant_id,
			String store_name, Integer total_fee, String currency,
			String content, String goods_count, String goods_detail,
			String diag_detail, Boolean is_tip, String buyer_name,
			String buyer_cellphone, String page_callback,
			String order_callback, String comment,String busi_type, String token,
			String operator_id, String operator_name, String order_total_fee,
			String discount_fee, String discount_comment, String detail,
			String ext1, String ext2) {
		CreateVo createVo = new CreateVo();
        if (StringUtil.isEmpty(merchant_id)) {
            log.error("merchant_id:" + merchant_id + "商户编号为必填项不能为空");
            createVo.setResp_status("9999");
            return createVo;
        }
        if (StringUtil.isEmpty(merchant_order_id)) {
            log.error("merchant_id:" + merchant_order_id + "商户编号为必填项不能为空");
            createVo.setResp_status("9999");
            return createVo;
        }
        if (StringUtil.isEmpty(total_fee.toString())) {
        	log.error("total_fee:" + total_fee.toString() + "订单总金额 为必填项不能为空");
        	createVo.setResp_status("9999");
        	return createVo;
        }
        //----------订单表 order_data
        String ORDERID = IdGenerator.getId();
        OrderDataEntity orderData = new OrderDataEntity();
        orderData.setId(ORDERID);
        orderData.setMerId(merchant_id);
        Calendar c = Calendar.getInstance();
        orderData.setOrdRegTime(TimeUtil.getTime(c.getTime()));
        c.add(Calendar.DAY_OF_MONTH, 1);//当前时间加一天
        orderData.setOrdExprTime(TimeUtil.getTime(c.getTime()));
        orderData.setPayStat("0000");
        orderData.setOrdStat("0000");
        orderData.setRefundCnt("0");
        orderData.setRefundAmt("0");
        orderData.setMerOrdId(merchant_order_id);
        orderData.setOrdAmt(total_fee.toString());
        orderData.setOrdCry(currency);
        orderData.setOperatorId(operator_id);
        orderData.setOperatorName(operator_name);
        iOrderDataDao.insert(orderData);//--插入订单表
        
        //----------订单附属表  order_affiliated
        OrderAffiliatedEntity affiEntity = new OrderAffiliatedEntity();
        if (is_tip == true) {
        	affiEntity.setIsTip(1 + "");
        } else {
        	affiEntity.setIsTip(0 + "");
        }
        affiEntity.setId(IdGenerator.getId());
        affiEntity.setOrderId(ORDERID);
        affiEntity.setModuleId(module_id);
        affiEntity.setOrderVersion("v0.3");
        affiEntity.setOrderContent(content);
        affiEntity.setBuyerName(buyer_name);
        affiEntity.setBuyerCellphone(buyer_cellphone);
        affiEntity.setOrderComment(comment);
        affiEntity.setOrderTotalFee(order_total_fee);
        affiEntity.setDiscountFee(discount_fee);
        affiEntity.setDiscountComment(discount_comment);
        affiEntity.setBusiType(busi_type);
        iOrderAffiliatedDao.insert(affiEntity);//--插入订单附属表

        //----------诊断信息表 diag_data
        DiagDataEntity diagEntity = null;
        String crd_user = IdGenerator.getId();//操作员
        String upd_user = IdGenerator.getId();//操作员编号
        if (StringUtil.isNotEmpty(detail)) {
        	List<Map<String, Object>> detailList = JSONUtil.fromJSON(detail, new TypeReference<List<Map<String, Object>>>(){});
			for (int i = 0; i < detailList.size(); i++) {
				Map<String, Object> detailMap = detailList.get(i);
				diagEntity = new DiagDataEntity();
				diagEntity.setId(IdGenerator.getId());
                diagEntity.setOrdId(ORDERID);
                diagEntity.setMerId(merchant_id);
                diagEntity.sethId((String) detailMap.get("his_id"));
                diagEntity.sethName((String) detailMap.get("his_name"));
                diagEntity.setDiagCode((String) detailMap.get("diag_id"));
                diagEntity.setDiagName((String) detailMap.get("diag_name"));
                diagEntity.setDiagComment((String) detailMap.get("diag_comment"));
                diagEntity.setCrdTime(new Date());
                diagEntity.setCrdUser(crd_user);
                diagEntity.setUpdTime(new Date());
                diagEntity.setUpdUser(upd_user);
                diagEntity.setState("1");
                iDiagDataDao.insert(diagEntity);//----插入诊信息

                //----------订单药品明细表 order_detail_data
                OrderDetailDataEntity detailEntity = null;
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> goods = (List<Map<String, Object>>)detailMap.get("goods");
    			if (goods != null) {
    				for (int j = 0; j < goods.size(); j++) {
    					Map<String, Object> good = goods.get(j);
        				detailEntity = new OrderDetailDataEntity();
        				detailEntity.setId(IdGenerator.getId());
                        detailEntity.setOrdId(ORDERID);
                        detailEntity.setMerId(merchant_id);
                        detailEntity.setMerOrdId(merchant_order_id);
                        detailEntity.setWaresId((String)good.get("goods_id"));
                        detailEntity.setWaresType((String)good.get("goods_type"));
                        detailEntity.setApCode((String)good.get("ap_code"));
                        detailEntity.setBatNo((String)good.get("bat_no"));
                        detailEntity.setLogCode((String)good.get("log_code"));
                        detailEntity.setNdCode((String)good.get("nd_code"));
                        detailEntity.setMiCode((String)good.get("mi_code"));
                        detailEntity.setMiType((String)good.get("mi_type"));
                        detailEntity.setWaresName((String)good.get("goods_name"));
                        detailEntity.setCmName((String)good.get("cm_name"));
                        detailEntity.setChName((String)good.get("ch_name"));
                        detailEntity.setStd((String)good.get("std"));
                        detailEntity.setPrice(Long.parseLong(good.get("goods_price").toString()));
                        detailEntity.setCurrency(currency);
                        detailEntity.setQuantity(Long.parseLong(good.get("goods_quantity").toString()));
                        detailEntity.setAmount((long) (Integer.parseInt(good.get("goods_price").toString()) * Integer.parseInt(good.get("goods_quantity").toString())));
                        detailEntity.setShowUrl((String)good.get("goods_url"));
                        detailEntity.setDetailComment((String) detailMap.get("diag_comment"));
                        detailEntity.setCrdUser(crd_user);
                        detailEntity.setUpdUser(upd_user);
                        detailEntity.setState("1");
                        iOrderDetailDataDao.insert(detailEntity);//---插入药品明细表
    				}
				}//end with (goods != null)
			}//end with detailList forearch
		}//end with (detail != null)
        
        //返回渠道JSONstr
        List<ChannelEntity> channels = new ArrayList<ChannelEntity>();
        channels = iChannelDao.listAll();
        List<Map<String, Object>> channelList = new ArrayList<Map<String, Object>>();
		Map<String, Object> channelMap = null;
		for (ChannelEntity enty : channels) {
			channelMap = new HashMap<String, Object>();
			channelMap.put("id", enty.getId());
			channelMap.put("channel_name", enty.getChannelName());
			channelMap.put("channel_type", enty.getChannelType());
			channelMap.put("channel_amt", "10000");
			channelMap.put("channel_comment", enty.getChannelFeeType());
			channelList.add(channelMap);
		}
		createVo.setResp_status(Constant.RESP_STAT_CODE_0000);
        createVo.setOrder_id(ORDERID);
        createVo.setChannel(JSONUtil.toJSON(channelList, List.class));
        createVo.setMsg(Constant.RESP_STAT_MSG_0000);
        createVo.setSign("translkdjgersign");
        log.info("订单创建完成_v0.3");
		return createVo;
	}


	/**
	 * 创建订单并支付
	 */
	@Override
	public CreateVo createOrderAndPay(String module_id, String version,
			String sign, String merchant_order_id, String merchant_id,
			String store_name, Integer total_fee, String currency,
			String content, String goods_count, String goods_detail,
			String diag_detail, Boolean is_tip, String buyer_name,
			String buyer_cellphone, String page_callback,
			String order_callback, String comment,String busi_type, String token,
			String operator_id, String operator_name, String order_total_fee,
			String discount_fee, String discount_comment, String detail,
			String ext1, String ext2, String local_pay_ssn, String fee,
			String channel_id, String buyer_token, String buyer_voucher,
			String channel_type) {
		CreateVo createVo = new CreateVo();
		createVo = this.createOrderV002(module_id, version, sign, merchant_order_id, merchant_id, store_name, total_fee, currency, content, goods_count, goods_detail, diag_detail, is_tip, buyer_name, buyer_cellphone, page_callback, order_callback, comment, busi_type, buyer_token, operator_id, operator_name, order_total_fee, discount_fee, discount_comment, detail, ext1, ext2);
		if ("0000".equals(createVo.getResp_status())) {
			String orderId = createVo.getOrder_id();
			PayOrderVo payOrderVo = payOrderServices.payOrder(module_id, version, local_pay_ssn, orderId, fee, currency, channel_id, buyer_token, buyer_voucher, channel_type, null);
			createVo.setResp_status(payOrderVo.getResp_status());
			createVo.setMsg(payOrderVo.getResp_msg());
			createVo.setSub_deal_stauts(payOrderVo.getSub_deal_stauts());
			createVo.setSub_deal_ssn(payOrderVo.getSub_deal_ssn());
			createVo.setSign("translkdjgersign");
		}
		return createVo;
	}
}
